<?php
namespace app\admin\service;

use library\tools\Node;
use think\Db;
use think\facade\Request;
use app\admin\service\MemberService;
/**
 * 系统公司管理服务
 * Class CompanyService
 * @package app\admin\service
 */
class CompanyService
{    
    
    /**
     * 检测公司是否存在
     * @param string $id
     * @return boolean
     */
    public static function company_check($id)
    {
    	$result = Db::name('system_company')->where(['id'=>$id])->count();
    	if($result){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    
    /**
     * 根据公司ID获取公司基本信息
     * @param string $id
     * @param string $field
     * @return array
     */
    public static function company_info($id,$field)
    {
    	if($field == '*'){
    		$info = Db::name('system_company')->where(['id'=>$id])->find();
    	}else{
    		$info = Db::name('system_company')->where(['id'=>$id])->field($field)->find();
    	}   	
    	if($info){
    		return $info;
    	}else{
    		return [];
    	}
    }
	
	
     /**
     * 获取所有的主/子账户类型公司
     * @param int $type  账户类型  1主    2子
	 * @param int $exclude  是否排除自身   1排除   0不排除
     * @return array
     */
    public static function account_type($type,$exclude = 0)
	{
		$where[] = ['account_type','eq',$type];
		if($exclude){
			$where[] = ['id','neq',$exclude];
		}	
		$ids = Db::name('system_member')->where($where)->column('id');
		if(!$ids){
			return [];
		}
		$list = Db::name('system_company')->where(['mid'=>$ids])->order('id desc')->column('name','id');	
		return $list;	
	}
	
	
	/**
     * 根据合同状态获取公司
     * @param int $type  合同状态  1未签合同或合同已失效     2已签合同且合同生效
	 * @param int $csr_id  客服ID
     * @return array
     */
    public static function canContract($type,$csr_id = 0)
	{
		if($csr_id){
			$where[] = ['sct.csr_id','eq',$csr_id];
		}		
		$where[] = ['sct.status','in',[1,2]];	
		$ids = Db::name('system_company')
				->alias('scy')->join('system_contract sct','sct.company_id=scy.id')
				->where($where)
				->column('scy.id');
		if($type == 1){
			if($ids){
				$list = Db::name('system_company')->where('id','notIn',$ids)->where('status','eq',2)->order('sort desc,id desc')->column('name','id');
			}else{
				$list = Db::name('system_company')->where('status','eq',2)->order('sort desc,id desc')->column('name','id');
			}
		}else{
			if(!$ids){
				return [];
			}
			$list = Db::name('system_company')->where(['id'=>$ids])->order('sort desc,id desc')->column('name','id');
		}			
		return $list;	
	}

   
    /**
     * 公司增加/扣除服务点
     * @param int $id 公司ID
	 * @param int $point 点数
	 * @param int $type 类型   1增加   2减少
     * @return array
     */
    public static function pointChange($id,$point,$type)
    {
    	$info = Db::name('system_company')->where(['id'=>$id])->find();
    	if($info){
    		if($type == 1){
    			$point = $info['point'] + $point;
    		}else{
    			$point = $info['point'] - $point;
    		}
    		$re = Db::name('system_company')->where(['id'=>$id])->update(['point'=>$point]);
			if($re){			
				$return = ['status'=>1,'msg'=>'增加/扣除成功'];
			}else{
				$return = ['status'=>0,'msg'=>'增加/扣除失败，请稍后再试'];
			} 
	    }else{
	   		$return = ['status'=>0,'msg'=>'公司不存在'];
	    } 	    
        return $return;
    }


	/**
     * 根据公司ID获取公司账户类型
     * @param int $id 公司ID
     * @return int
     */
    public static function getAccountType($id)
	{
		$company = Db::name('system_company')->where(['id'=>$id])->find();
		$member = Db::name('system_member')->where(['id'=>$company['mid']])->find();
		return $member['account_type'];
	}
	
	
	/**
     * 根据公司ID获取公司主账户信息
     * @param int $id 公司ID
     * @return array
     */
    public static function getMaster($id)
	{
		$company = Db::name('system_company')->where(['id'=>$id])->find();
		$member = Db::name('system_member')->where(['id'=>$company['mid']])->find();
		if($member['account_type'] == 2){
			$company = Db::name('system_company')->where(['id'=>$member['master']])->find();
		}
		return $company;
	}
	
	
	/**
     * 根据公司ID获取公司主账户以及子账户id集合
     * @param int $id 公司ID
     * @return array
     */
    public static function getAllId($id)
	{ 		
		$master = self::getMaster($id);
		$slavemids = Db::name('system_member')->where(['account_type'=>2,'master'=>$master['id']])->column('id');		
		if($slavemids){
			$ids = Db::name('system_company')->where(['mid'=>$slavemids])->column('id');
			$ids[] = $master['id'];
		}else{
			$ids[] = $id;
		}
		return $ids;
	}
	
	
	/**
     * 公司员工表状态变更
     * @param int $person_id 	个人ID
	 * @param int $company_id 	公司ID
	 * @param int $status 状态    	1在职      3离职
	 * @param int $increase_id 	增员委托表ID
     * @return array
     */
    public static function companyPerson($person_id,$company_id,$status,$increase_id)
	{
		$count = Db::name('system_company_person')->where(['person_id'=>$person_id,'company_id'=>$company_id])->count();
		if($count){
			Db::name('system_company_person')->where(['person_id'=>$person_id,'company_id'=>$company_id])->update(['status'=>$status,'increase_id'=>$increase_id]);
		}else{
			$code = Db::name('system_person')->where(['id'=>$person_id])->value('code');
			$data = [
				'increase_id' => $increase_id,
				'person_id' => $person_id,
				'company_id' => $company_id,
				'person_code' => $code,
				'status' => $status
			];
			Db::name('system_company_person')->insert($data);
		}
		
	}

       
    
    /**
     * 导出公司
     * @param array $id
     * @return array
     */
    public static function export_company($id)
    {
    	$filename = '公司列表';
    	$titles = array(
    		array('unique','公司编号'),
            array('name','公司名称'),
            array('account_type','账号类型'),
            array('master','上级公司'),
            array('mobile','手机号码'),
            array('company_add','联系地址'),
            array('taxid','税务身份'),
            array('invoice','发票类型'),
            array('tax_number','公司税号'),
            array('invoice_add','公司地址'),
            array('company_tel','公司电话'),
            array('bank_account','银行账号'),
            array('bank','开户银行'),
            array('bank_number','银行行号'),
            array('csr_id','所属客服'),
            array('status','状态'),
            array('desc','备注信息'),
        );
    	$list = Db::name('system_company')->where(['id'=>$id])->order('sort desc,id desc')->select();
		$mids = Db::name('system_company')->where(['id'=>$id])->column('mid');
		if(!empty($list) && $list){
			$mobiles = Db::name('system_member')->where(['id'=>$mids])->column('mobile','id');
			$account_type = Db::name('system_member')->where(['id'=>$mids])->column('account_type','id'); 	 		
			$master = Db::name('system_member')->where(['id'=>$mids])->column('master','id');
			$company = 	Db::name('system_company')->column('name','id');
			foreach($list as $k=>$v){
	    		$arr[$k]['unique'] = $v['unique'];
	    		$arr[$k]['name'] = $v['name'];
				$arr[$k]['account_type'] = $account_type[$v['mid']] == 1 ? '主账号' : '子账号';
				$arr[$k]['master'] = $master[$v['mid']] == 0 ? '' : $company[$master[$v['mid']]];
				$arr[$k]['mobile'] = $mobiles[$v['mid']];
	    		$arr[$k]['company_add'] = $v['company_add'];
				$arr[$k]['taxid'] = $v['taxid'] ? get_option('taxid')[$v['taxid']] : '';
				$arr[$k]['invoice'] = $v['invoice'] ? get_option('invoice')[$v['invoice']] : '';
	    		$arr[$k]['tax_number'] = $v['tax_number'];
				$arr[$k]['invoice_add'] = $v['invoice_add'];
				$arr[$k]['company_tel'] = $v['company_tel'];
				$arr[$k]['bank_account'] = $v['bank_account'];
				$arr[$k]['bank'] = $v['bank'];
				$arr[$k]['bank_number'] = $v['bank_number'];
				$arr[$k]['csr_id'] = $v['csr_id'] ? user_list()[$v['csr_id']] : '';
				$arr[$k]['status'] = ['1'=>'待审核','2'=>'已审核'][$v['status']];
				$arr[$k]['desc'] = $v['desc'];
	    	}
		}else{
			$arr = [];
		}   
    	
        return ['filename'=>$filename,'titles'=>$titles,'list'=>$arr];
    }
    
    
	/**
	 * 导出签约订单
     * @param array $id
     * @return array
     */
    public static function export_signorder($id)
    {
    	$filename = '签约订单列表';
    	$titles = array(
    		array('code','订单编号'),
    		array('company_name','公司名称'),
            array('package_name','套餐名称'),                       
            array('receivable','应收金额'),
            array('arrival','实收金额'),
            array('balance','余额'),
            array('create_at','创建时间'),
            array('status','状态')
        );
    	$list = Db::name('system_package_order')->where(['id'=>$id])->order('id desc')->select();
		if(!empty($list) && $list){
			$companys = Db::name('system_company')->column('name','id');
			$packages = Db::name('system_package')->column('title','id');
			foreach($list as $k=>$v){
	    		$arr[$k]['code'] = $v['code'];
				$arr[$k]['company_name'] = $companys[$v['company_id']];
				$arr[$k]['package_name'] = $packages[$v['package_id']];
				$arr[$k]['receivable'] = $v['receivable'];
				$arr[$k]['arrival'] = $v['arrival'];
				$arr[$k]['balance'] = $v['balance'];									    		
				$arr[$k]['create_at'] = date('Y-m-d',strtotime($v['create_at']));
				$arr[$k]['status'] = ['1'=>'待付款','2'=>'待核对','3'=>'待签约','4'=>'已签约','5'=>'已取消'][$v['status']];
	    	}
		}else{
			$arr = [];
		}   
    	
        return ['filename'=>$filename,'titles'=>$titles,'list'=>$arr];
    }
    
    
    /**
	 * 导出续约订单
     * @param array $id
     * @return array
     */
    public static function export_renewalorder($id)
    {
    	$filename = '续约订单列表';
    	$titles = array(
    		array('code','订单编号'),
    		array('company_name','公司名称'),
            array('package_name','套餐名称'),                       
            array('receivable','应收金额'),
            array('arrival','实收金额'),
            array('balance','余额'),
            array('create_at','创建时间'),
            array('status','状态')
        );
    	$list = Db::name('system_package_order')->where(['id'=>$id])->order('id desc')->select();
		if(!empty($list) && $list){
			$companys = Db::name('system_company')->column('name','id');
			$packages = Db::name('system_package')->column('title','id');
			foreach($list as $k=>$v){
	    		$arr[$k]['code'] = $v['code'];
				$arr[$k]['company_name'] = $companys[$v['company_id']];
				$arr[$k]['package_name'] = $packages[$v['package_id']];
				$arr[$k]['receivable'] = $v['receivable'];
				$arr[$k]['arrival'] = $v['arrival'];
				$arr[$k]['balance'] = $v['balance'];									    		
				$arr[$k]['create_at'] = date('Y-m-d',strtotime($v['create_at']));
				$arr[$k]['status'] = ['1'=>'待付款','2'=>'待核对','3'=>'待续约','4'=>'已续约','5'=>'已取消'][$v['status']];
	    	}
		}else{
			$arr = [];
		}   
    	
        return ['filename'=>$filename,'titles'=>$titles,'list'=>$arr];
    }
    
}
